<template>
  <div class="query-collect-container">
    <div class="layout-container">
      <div class="sidebar">
        <p style="margin-bottom: 10px;">脚本选择</p>
        <el-menu default-active="2" class="el-menu-vertical-demo" @select="handleMenuSelect" background-color="#092742"
          text-color="#fff" active-text-color="#fff" :unique-opened="true">
          <el-submenu v-for="category in categories" :key="category.id" :index="category.id.toString()">
            <template slot="title">
              <span>{{ category.name }}</span>
            </template>
            <el-menu-item-group>
              <el-menu-item v-for="item in category.items" :key="item.id" :index="`${category.id}-${item.id}`">
                {{ item.name }}
              </el-menu-item>
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </div>

      <!-- 右侧主内容区 -->
      <div class="main-content">
        <!-- 初始状态 -->
        <div v-if="!currentCategory" class="empty-state">
          <p>请选择左侧菜单查看数据</p>
        </div>

        <!-- 属性表格 -->
        <div v-else-if="currentView === 'attribute'" class="attribute-table-container">
          <!-- <h3>{{ currentCategory }} - 属性列表</h3> -->
          <!-- 有数据时显示表格 -->
          <el-table v-if="attributeList && attributeList.length > 0" :data="attributeList" border >
            <el-table-column prop="field" label="字段" align="center"></el-table-column>
            <el-table-column prop="explanation" label="字段解释" align="center"></el-table-column>
          </el-table>
          <!-- 无数据时显示提示信息 -->
          <div v-else class="empty-data">
            <p>暂无属性数据</p>
          </div>
        </div>

        <!-- 内容表格 -->
        <div v-else-if="currentView === 'content'" class="content-table-container">
          <!-- <h3>{{ currentCategory }} - 内容数据</h3> -->
          <!-- 有数据时显示搜索框、按钮、表格和分页 -->
          <div v-if="tableData && tableData.length > 0">
            <div style="display: flex; justify-content: space-between; align-items: center;margin-bottom: 20px;">
              <div>
                <span style="margin-right: 10px;">产品查询</span>
                <el-input v-model="searchProduct" placeholder="请输入产品名称" clearable style="width: 200px;"></el-input>
              </div>
              <div style="display: flex; justify-content: space-between; align-items: center;">

                <button type="primary" size="small" @click="queryCollectData(currentCategory)" icon="el-icon-refresh-left"
                  class="resetbutton2">
                  <span>查询</span>
                  <i class="el-icon-search"></i>

                </button>
                <button type="primary" size="small" @click="resetSearch" icon="el-icon-refresh-left" class="resetbutton">
                  <span>重置</span>
                  <i class="el-icon-refresh-left"></i>

                </button>
              </div>
            </div>
            <el-table :data="tableData" style="width: 100%" border :header-cell-style="{background:'#2CDFE8',color:'#ffffff'}">
              <el-table-column
                v-for="column in dynamicColumns"
                :key="column.prop"
                :prop="column.prop"
                :label="column.label"
                :align="column.align"
                :show-overflow-tooltip="column.showOverflowTooltip"
              ></el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              
              :total="listTotal">
            </el-pagination>
          </div>
          <!-- 无数据时显示提示信息 -->
          <div v-else class="empty-data">
            <p>暂无数据</p>
            <!-- <el-empty description="暂无数据"></el-empty> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getCollectData } from '@/api/user'
export default {
  data() {
    return {
      categories: [
        { id: 1, name: '广播电视通信', items: [{ id: 1, name: '属性' }, { id: 2, name: '内容' }] },
        { id: 2, name: '固定通信', items: [{ id: 1, name: '属性' }, { id: 2, name: '内容' }] },
        { id: 3, name: '数据通信', items: [{ id: 1, name: '属性' }, { id: 2, name: '内容' }] },
        { id: 4, name: '卫星通信', items: [{ id: 1, name: '属性' }, { id: 2, name: '内容' }] },
        { id: 5, name: '蜂窝移动通信', items: [{ id: 1, name: '属性' }, { id: 2, name: '内容' }] },
        { id: 6, name: '通信设备制造', items: [{ id: 1, name: '属性' }, { id: 2, name: '内容' }] },
        { id: 7, name: '通信网络规划与建设', items: [{ id: 1, name: '属性' }, { id: 2, name: '内容' }] },
        { id: 8, name: '电信增值', items: [{ id: 1, name: '属性' }, { id: 2, name: '内容' }] }
      ],
      pageSize: 10,
      pageNum: 1,
      currentCategory: '',
      currentView: '',
      attributeList: [],
      tableData: [],
      listTotal: 0,
      currentPage: 1,
      searchProduct: '',
      dynamicColumns: [], // 存储动态生成的表格列配置
    };
  },
  methods: {
    queryCollectData(categoryName) {
      getCollectData({
        type: categoryName,
        queryName: this.searchProduct,
        pageSize: this.pageSize,
        pageNum: this.pageNum
      }).then(res => {
        console.log('获取的数据：', res)

        // 模拟接口返回数据，实际应使用res.data


        const data = res.data

        if (this.currentView === 'attribute') {
          // 直接使用接口返回的attribute数组
          this.attributeList = (data.attribute || []).map(item => ({
            field: item.table,
            explanation: item.tableName,
            example: '' // 由于没有实际数据，示例留空
          }));
        } else if (this.currentView === 'content') {
          // 格式化时间并存储表格数据
          this.tableData = (data.tableList && data.tableList.rows || []).map(row => ({
            ...row,
            time: this.formatTime(row.time)
          }));
          // 设置总条数
          this.listTotal = data.tableList.total || 0;
          
          // 生成动态表格列配置
          this.generateDynamicColumns();
        }
      })
    },
    resetSearch() {
      this.searchProduct = ''
      this.queryCollectData(this.currentCategory)
    },
    // 生成动态表格列配置
    generateDynamicColumns() {
      if (!this.tableData || this.tableData.length === 0) {
        this.dynamicColumns = [];
        return;
      }
      
      // 获取第一行数据的所有字段
      const firstRow = this.tableData[0];
      const columns = [];
      
      // 定义字段解释映射
      const fieldExplanations = {
        'PId': '产品ID',
        'PName': '产品名称',
        'PCategory': '产品类别',
        'PCommInterface': '通信接口',
        'PPower': '电源',
        'PMountWay': '安装方式',
        'PWeight': '产品重量',
        'PScreenType': '屏幕类型',
        'POtherParam': '其他参数',
        'time': '时间',
        'PModel': '产品型号',
        'PType': '产品类型',
        'PColor': '产品颜色',
        'PInterface': '接口',
        'PSpeed': '速度',
        'PSaleScope': '销售范围',
        'PSize': '产品尺寸',
        'POutputWay': '输出方式',
        'PPolarization': '极化方式',
        'PPolarizationType': '极化类型',
        'PProdType': '产品类型',
        'PRecvBand': '接收频段',
        'PCableType': '电缆类型',
        'PCoreMm': '核心尺寸（mm）',
        'PImpedanceOhm': '阻抗（欧姆）',
        'PMaterial': '材料',
        'POuterMm': '外部尺寸（mm）',
        'PVelocityRatio': '速度比',
        'PBatteryLife': '电池寿命',
        'PFrequencyBand': '工作频段',
        'PPowerConsumption': '功耗',
        'PTechStd': '技术规格',
        'PTxPower': '发射功率',
        'PFrequencyBands': '工作频段',
        'txPower': '发射功率',
        'PProtocol': '通信协议',
        'PInputVoltage': '输入电压',
        'POutCurrent': '输出电流',
        'POutPower': '输出功率',
        'POutVoltage': '输出电压',
        'PLifeCycle': '生产周期',
        'PPackage': '产品包装',
        'PRohs': 'Rohs认证',
        'PSummary': '产品总结',
        'PWorkTem': '工作温度',
        'PWorkVoltage': '工作电压',
      };
      
      // 遍历字段生成列配置
      for (const field of Object.keys(firstRow)) {
        // 排除不需要显示的字段
        if (field !== 'grouping' && field !== 'POtherParam') {
          columns.push({
            prop: field,
            label: fieldExplanations[field] || field,
            align: 'center',
            showOverflowTooltip: true
          });
        }
      }
      
      this.dynamicColumns = columns;
    },
    
    // 生成属性列表
    generateAttributeList(rows) {
      if (!rows || rows.length === 0) return [];

      // 获取第一行数据作为示例
      const firstRow = rows[0];
      const attributes = [];

      // 定义字段解释映射
      const fieldExplanations = {
        'PId': '产品ID',
        'PName': '产品名称',
        'PModel': '产品型号',
        'PType': '产品类型',
        'PColor': '产品颜色',
        'PInterface': '产品接口',
        'PSpeed': '产品速度',
        'PSaleScope': '销售范围',
        'POtherParam': '其他参数',
        'time': '时间',
        'PSize': '产品尺寸',
        'POutputWay': '输出方式',
        'PPolarization': '极化方式',
        'PPolarizationType': '极化类型',
        'PProdType': '产品类型',


      };

      // 遍历字段生成属性列表
      for (const [field, value] of Object.entries(firstRow)) {
        if (field !== 'grouping') { // 排除grouping字段
          let example = value;
          // 限制示例长度
          if (typeof example === 'string' && example.length > 50) {
            example = example.substring(0, 50) + '...';
          }

          attributes.push({
            field: field.toLowerCase(), // 转换为小写
            explanation: fieldExplanations[field] || field,
            example: example
          });
        }
      }

      return attributes;
    },

    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return '';
      // 假设时间字符串已经是正确格式 "2025-11-27 11:25:04"
      return timeStr;
    },
    handleMenuSelect(index) {
      // 解析index获取分类和项目信息
      const [categoryId, itemId] = index.split('-');
      const category = this.categories.find(c => c.id === parseInt(categoryId));
      const item = category ? category.items.find(i => i.id === parseInt(itemId)) : null;

      if (category && item) {
        console.log(`选择了分类：${category.name}，项目：${item.name}`);
        // 记录当前选择的分类和视图类型
        this.currentCategory = category.name;
        this.currentView = item.name === '属性' ? 'attribute' : 'content';
        // 重置页码为第一页
        this.pageNum = 1;
        // 调用接口获取数据
        this.queryCollectData(category.name);
      }
    },

    // 处理每页条数变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.queryCollectData(this.currentCategory);
    },

    // 处理页码变化
    handleCurrentChange(val) {
      console.log('当前页码:', val);
      this.pageNum = val;
      this.queryCollectData(this.currentCategory);
    }

  }
};
</script>

<style scoped>
.query-collect-container {
  min-height: 90vh;
  background-color: #04142B;
  color: #FFFFFF;
  font-family: Alibaba PuHuiTi, Alibaba PuHuiTi;
  max-width: 1600px;
  margin: 0 auto;
}

.layout-container {
  height: 100%;
  padding: 20px;
  display: flex;
  align-content: center;
  justify-content: space-between;
}

.sidebar {
  width: 335px;
  height: 755px;
  background: #182F50;
  border-radius: 10px;
  border: 0.5px solid rgba(44, 223, 232, 0.5);
  padding: 20px;
}

.main-content {
  width: 1185px;
  height: 755px;
  background: #182F50;
  border-radius: 10px 10px 10px 10px;
  border: 0.5px solid rgba(44, 223, 232, 0.5);
  padding: 20px;
}

.empty-data {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #FFFFFF;
  font-size: 16px;
}








/* 导航栏 */
:deep(.el-menu) {
  background-color: transparent;
  border-right: none;
  border: 0.5px solid rgba(0,163,255,0.5);
}

:deep(.el-submenu) {
  /* border: 0.5px solid rgba(221, 221, 221, 0.5); */
}

:deep(.el-menu-item-group__title) {
  padding: 0;
}

:deep(.el-menu-item) {
  color: #FFFFFF;
  border: none;
}
:deep(.el-menu-item:hover) {
 background: linear-gradient( 90deg, #0085FF 0%, rgba(0,163,255,0) 100%);
}
:deep(.el-menu-item:focus) {
 background: linear-gradient( 90deg, #0085FF 0%, rgba(0,163,255,0) 100%);
}

:deep(.el-submenu__title) {
  color: #FFFFFF;
  border-bottom: 0.5px solid rgba(221, 221, 221, 0.5);

}

:deep(.el-submenu__title i) {
  color: #FFFFFF;
  font-size: 12px;
}

/* 表格 */

/* 查询 重置按钮 */

.resetbutton {
  width: 92px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  font-size: 12px;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #182F50;
  transform: skew(-10deg);
  border-radius: 0px 0px 0px 0px;
  border: 1px solid;
  border-radius: 4px;
  border-image: linear-gradient(136deg, rgba(44, 223, 232, 1), rgba(26, 154, 219, 1), rgba(26, 154, 217, 1)) 1 1;
}

.resetbutton span {
  transform: skew(10deg);
}

/* 移除重置按钮点击时的黑色边框 */
.resetbutton:focus {
  outline: none !important;
  border: 1px solid #1A9AD9;
  background: #182F50;
}

.resetbutton2 {
  width: 92px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  font-size: 12px;
  color: #fff;
  display: flex;
  margin: 0px 10px;

  align-items: center;
  justify-content: center;
  /* background: #182F50; */
  transform: skew(-10deg);
  background: linear-gradient(180deg, rgba(0, 135, 255, 0.25) 0%, rgba(0, 135, 255, 0.52) 100%);
  border-radius: 0px 0px 0px 0px;
  border: 1px solid;
  border-image: linear-gradient(136deg, rgba(44, 223, 232, 1), rgba(26, 154, 219, 1), rgba(26, 154, 217, 1)) 1 1;
}

.resetbutton2 span {
  transform: skew(10deg);
}

/* 移除重置按钮点击时的黑色边框 */
.resetbutton2:focus {
  outline: none !important;
  border: 1px solid #1A9AD9;
  background: #182F50;
}

.resetbutton2:hover {
  background: linear-gradient(360deg, #0085FF 0%, rgba(0, 163, 255, 0) 100%);
  border-radius: 0px 0px 0px 0px;
  border: 1px solid;
  border-image: linear-gradient(180deg, rgba(0, 163, 255, 0), rgba(0, 163, 255, 1)) 1 1;
  border-top: none;
}



/* 查询重置 */
/* 移除额外的边框和强制背景色设置 */
::v-deep .el-table,
::v-deep .el-table__expanded-cell {
  background-color: transparent !important;
}

/* 表格内背景颜色 */
::v-deep .el-table th,
::v-deep .el-table tr,
::v-deep .el-table td {
  background-color: transparent !important;
  border: 1px solid rgba(221, 221, 221, 0.5);
  color: #FFFFFF;
}

/*去除底边框*/
::v-deep.el-table td.el-table__cell {
  border: 1px solid rgba(221, 221, 221, 0.5);

}

::v-deep.el-table th.el-table__cell.is-leaf {
  border: 1px solid rgba(221, 221, 221, 0.5);

}

/*去除底部灰条.el-table::before*/
::v-deep .el-table::before {
  display: none;
}

/* 分页样式 */
::v-deep .el-pagination {
  margin-top: 20px;
  text-align: right;
}

::v-deep .el-pagination button,
::v-deep .el-pagination span:not(.el-pagination__total) {
  color: #FFFFFF;
}

::v-deep .el-pagination .btn-prev,
::v-deep .el-pagination .btn-next,
::v-deep .el-pagination .el-pager li {
  background-color: transparent;
  border: 1px solid rgba(221, 221, 221, 0.5);
  color: #FFFFFF;
}

::v-deep .el-pagination .el-pager li:hover,
::v-deep .el-pagination .el-pager li.active {
  background-color: #fff;
  color: #1A3B6B;
}

::v-deep .el-pagination .btn-prev:hover,
::v-deep .el-pagination .btn-next:hover {
  background-color: #fff;
  color: #1A3B6B;

}

::v-deep .el-pagination .btn-prev,
::v-deep .el-pagination .btn-next {
  background: rgba(230, 247, 255, 0.2);
  color: #fff;

}

::v-deep .el-pagination__sizes .el-input .el-input__inner {
  background-color: transparent;
  border: 1px solid rgba(221, 221, 221, 0.5);
  color: #FFFFFF;
}

::v-deep .el-pagination__total {
  color: #FFFFFF;
}

::v-deep .el-pagination__editor.el-input .el-input__inner {
  background: rgba(230, 247, 255, 0.2);
  color: #FFFFFF;
}


/* 输入框 */
:deep(.el-input__inner) {
  background-color: #152133;
  border: 1px solid #fff;
  color: #ffffff;
  transform: skew(-5deg);

}
</style>